package com.ruoyi.system.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.exception.user.UserPasswordRepeatException;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.domain.User;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.IUserService;

/**
 * 用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-11
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;


    /**
     * 查询用户
     * 
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public User selectUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询用户列表
     * 
     * @param user 用户
     * @return 用户
     */
    @Override
    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增用户
     * 
     * @param user 用户
     * @return 结果
     */
    @Override
    public int insertUser(User user) {
        user.setCreateTime(DateUtils.getNowDate());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return userMapper.insertUser(user);
    }

    /**
     * 修改用户
     * 
     * @param user 用户
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        user.setUpdateTime(DateUtils.getNowDate());
        if (!StringUtils.isEmpty(user.getPassword())) {
            String pass = user.getPassword();
            String password = SecurityUtils.encryptPassword(pass);
            User oldUser = userMapper.selectUserInfoById(user.getId());
            if (SecurityUtils.matchesPassword(pass, oldUser.getPassword())) {
                throw new ServiceException("新密码与旧密码相同");
            } else {
                user.setPassword(password);
            }
        }
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除用户
     * 
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] ids) {
        return userMapper.deleteUserByIds(ids);
    }

    /**
     * 删除用户信息
     * 
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteUserById(Long id) {
        return userMapper.deleteUserById(id);
    }

    /**
     * 根据状态查询用户列表
     * 
     * @param status 用户状态
     * @return 用户列表
     */
    @Override
    public List<User> selectUserListByStatus(String status) {
        return userMapper.selectUserListByStatus(status);
    }

    /**
     * 修改用户状态
     * 
     * @param id     用户ID
     * @param status 用户状态
     * @return 结果
     */
    @Override
    public int updateUserStatus(Long id, String status) {
        return userMapper.updateUserStatus(id, status);
    }

    @Override
    public List<User> selectUsersByTop() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        Long bindUserId = sysUser.getBindUserId() == null ? Long.parseLong("0")
                : Long.parseLong(sysUser.getBindUserId());
        return userMapper.selectUsersByTop(bindUserId);
    }


    @Override
    public List<User> getNoAuditUser() {
        return userMapper.getNoAuditUser();
    }

    @Override
    public User selectUserByUserName(String username) {
        return userMapper.selectUserByUserName(username);
    }

    @Override
    public int resetPassword(Long id, String password) {
        if(password.length()<5 || password.length()>20){
            throw new UserException("user.password.not.valid", null);
        }
        User user = userMapper.selectUserById(id);
        // if(user.equals(null)){
        //     throw 
        // }
        password = SecurityUtils.encryptPassword(password);
        if(password == user.getPassword()){
            throw new UserPasswordRepeatException();
        }

        return userMapper.resetPassword(id, password);
    }

    @Override
    public String rigister(User user){
        validateCaptcha(user.getUsername(),user.getCode(),user.getUuid());
        user.setStatus("0");
        user.setIsDel("0");
        user.setType("0");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        User hasUser = userMapper.selectUserByUserName(user.getUsername());
        if(!hasUser.equals(null)){
            throw new UserException("user.is.exists", null);
        }
        int code = userMapper.insertUser(user);
        return code+"";
    }
        /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                // AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                // AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }
    
}
